<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Group4_UniHub</title>
  <link rel="stylesheet" href="css/student.css">
</head>
<body>
  <div class="header">
    <h1>Student Profiles</h1>
  </div>
  <div class="row">
    <div class="col-3 col-m-3 menu">
      <button class="Btn loginOutBtn">Log Out</button>
      <button class="Btn editProfileBtn">Edit My Profile</button>
      <ul>
        <li id="studentProfilesLink">Student Profiles</li>
        <li id="groupManagementLink">Group Management</li>
        <li id="campusNoticeboard">Campus Noticeboard</li>
      </ul>
    </div>
    <div class="col-9 col-m-9 content">
      <div class="search-container" id="searchContainer">
          <input type="text" id="searchInput" placeholder="Please enter a course to match students">
          <button id="searchButton">search</button>
      </div>
      <div class="profile-container" id="profileContainer">
        <table id="studentTable">
          <thead>
            <tr>
              <th>ID</th>
              <th>Photo</th>
              <th>Username</th>
              <th>Email</th>
              <th>Interests</th>
              <th>Courses</th>
              <th>Achievements</th>
              <th>Bio</th>
            </tr>
          </thead>
          <tbody>
            <!-- Data will be inserted here by JavaScript -->
          </tbody>
        </table>
      </div>
      <!-- Update Profile -->
       <form id="updateProfileForm" class="hidden">
        <h4>Update My profile</h4>
        <input type="hidden" id="update-id" name="id" required>
        <label>Photo:</label>
        <input type="file" id="update-photo" accept="image/*">
        <label>Interests:</label>
        <input type="text" id="update-interests" name="interests" required>
        <label>Courses:</label>
        <input type="text" id="update-courses" name="courses" required>
        <label>Achievements:</label>
        <input type="text" id="update-achievements" name="achievements" required>
        <label>Bio:</label>
        <textarea id="update-bio" name="bio" placeholder="Please enter your bio.No more than 40 words." required maxlength="40"></textarea>
        <button type="submit">Update my profile</button>
       </form>
    </div>
  </div>
  <footer>
    <p>Group4 : Gina22083649_Yani22083647_Quinn22083651_Iris22083648</p>
  </footer>
  <script>
    //Display all the profiles
    document.addEventListener('DOMContentLoaded', function() {
        fetch('/profiles', {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        })
        .then(response => response.json())
        .then(data => {
            const tableBody = document.querySelector('#studentTable tbody');
            data.forEach(student => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${student.ID}</td>
                    <td><img src="${student.Photo}" alt="Profile Photo" class="profile-photo"></td>              
                    <td>${student.Username}</td>
                    <td>${student.Email}</td>
                    <td>${student.Interests}</td>
                    <td>${student.Courses}</td>
                    <td>${student.Achievements}</td>
                    <td>${student.Bio}</td>
                `;
                tableBody.appendChild(row);
            });
        })
        .catch(error => console.error('Error fetching student data:', error));
    });

    document.querySelector('.editProfileBtn').addEventListener('click', function() {
    searchContainer.classList.add('hidden');
    profileContainer.classList.add('hidden');
    updateProfileForm.classList.remove('hidden');

    const userId = localStorage.getItem('userId');
    document.getElementById('update-id').value = userId;
});
    //Update Profile 
  document.getElementById("updateProfileForm").addEventListener("submit", function(event) {
      event.preventDefault();
      const id = document.getElementById('update-id').value;
      const formData = new FormData();
      formData.append('photo', document.getElementById('update-photo').files[0]);
      formData.append('interests', document.getElementById('update-interests').value);
      formData.append('courses', document.getElementById('update-courses').value);
      formData.append('achievements', document.getElementById('update-achievements').value);
      formData.append('bio', document.getElementById('update-bio').value);

      fetch(`http://localhost:3000/profiles/${id}`, {
          method: 'PUT',
          headers: {
              'Authorization': `Bearer ${localStorage.getItem('token')}`
          },
          body: formData
      })
      .then(res => res.json())
      .then(data => {
          console.log('Updated results.', data);
          alert('Profile updated successfully!');
          window.location.href = '/student';
      })
      .catch(error => {
          console.error('Error:', error);
          alert('Failed to update profile.');
      });
  });

  document.addEventListener('DOMContentLoaded', function() {
      const studentProfilesLink = document.getElementById('studentProfilesLink');
      const searchContainer = document.getElementById('searchContainer');
      const profileContainer = document.getElementById('profileContainer');
      const updateProfileForm = document.getElementById('updateProfileForm');
      const editProfileBtn = document.querySelector('.editProfileBtn');  
      const groupManagementLink = document.getElementById('groupManagementLink');  

      //Show Student profiles and hide other sections
      studentProfilesLink.addEventListener('click', function() {
        searchContainer.classList.remove('hidden');
        profileContainer.classList.remove('hidden');
        updateProfileForm.classList.add('hidden'); // 确保更新表单被隐藏
      });

      //Show Group Management and hide other sections
      groupManagementLink.addEventListener('click', function() {
        window.location.href = '/group';
      });

      //Show Edit Profile Form and hide other parts
      editProfileBtn.addEventListener('click', function() {
        searchContainer.classList.add('hidden');
        profileContainer.classList.add('hidden');
        updateProfileForm.classList.remove('hidden');
      });
      
      //Add a click event listener for the Log out button
      const logoutBtn = document.querySelector('.loginOutBtn');
      logoutBtn.addEventListener('click', function() {
        //Clear tokens stored in local storage
        localStorage.removeItem('token');

        //Redirect to/page
        window.location.href = '/';
      });

      //Add a click event listener with search function
      document.getElementById("searchButton").addEventListener("click", function() {
        const keyword = document.getElementById('searchInput').value;
        fetch(`/studentSearch?keyword=${encodeURIComponent(keyword)}`)
            .then(response => response.json())
            .then(data => {
                const tableBody = document.querySelector('#studentTable tbody');
                tableBody.innerHTML = ''; 
                data.forEach(student => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${student.ID}</td>
                        <td><img src="${student.Photo}" alt="Profile Photo" class="profile-photo"></td>
                        <td>${student.Username}</td>
                        <td>${student.Email}</td>
                        <td>${student.Interests}</td>
                        <td>${student.Courses}</td>
                        <td>${student.Achievements}</td>
                        <td>${student.Bio}</td>
                    `;
                    tableBody.appendChild(row);
                });
                updateProfileForm.classList.add('hidden');
            })
            .catch(error => console.error('Error fetching search results:', error));
      });
  });
  </script>
</body>
</html>